package com.copro.chemdb.stat.rule;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.LinkedList;
import java.util.List;

import org.ihelpuoo.db.sql.SQLSegment;
import org.ihelpuoo.lang.StringUtils;
import org.ihelpuoo.util.Properties;

import com.copro.chemdb.stat.AbstractStatRule;
import com.copro.chemdb.stat.StatResult;
import com.copro.chemdb.subject.Subject;
import com.copro.simple.Application;
import com.copro.simple.SimpleException;
import com.copro.simple.db.QueryCallback;
import com.copro.simple.db.QuickQueryCallback;

public class Rule3C3 extends AbstractStatRule {

	@Override
	public StatResult doStat(Application app, Subject subject, int statType)
			throws SimpleException {
		SQLSegment sql = app.getSQL("rule3c3.stat");
		sql.set("quesId", subject.getQuesId());
		sql.set("subjectId", subject.getId());
		sql.set("type", statType);
		List<List<String>> rows = new LinkedList<List<String>>();
		QueryCallback callback = new QuickQueryCallback(rows) {
			@SuppressWarnings("unchecked")
			@Override
			public void exec(ResultSet rs) throws SQLException {
				while (rs.next()) {
					List<String> list = new ArrayList<String>(3);
					list.add(rs.getString("content"));
					list.add(StringUtils.isBlank(rs.getString("extjob")) ? rs
							.getString("job") : rs.getString("extjob"));
					list
							.add(StringUtils
									.isBlank(rs.getString("extcomtype")) ? rs
									.getString("comtype") : rs
									.getString("extcomtype"));
					((List)obj).add(list);
				}
			}
		};
		app.query(sql.toString(), callback);
		Hashtable<String, Object> result = new Hashtable<String, Object>();

		sql = app.getSQL("rule3c3.count");
		sql.set("subjectId", subject.getId());
		sql.set("type", statType);
		int len = app.getCount(sql.toString());

		result.put("count", len);
		result.put("rows", rows);
		result.put("text", subject.getBrief());
		return new StatResult("rule3c3", result);
	}

	@Override
	public void setup(Properties conf) {
	}

}
